<template>
    <div class="app-container">
        <div class="header">
            <el-button type="primary" size="mini" @click="openSaveCostForm">添加</el-button>
            <el-input style="width: 300px; margin-left: 100px;" v-model="costListForm.memo" size="mini"
                placeholder="输入关键字搜索" @change="styleSearch" @input="checkVal">
                <i slot="suffix" class="el-icon-search"></i>
            </el-input>
        </div>

        <!-- 添加价格弹出框 -->
        <el-dialog title="添加商品价格" :visible.sync="showSaveCostForm" :close-on-click-modal="false" @close="closeSaveCostForm">
            <el-form ref="saveCostForm" :model="saveCostForm" label-width="100px" :rules="saveCostRules">
                <el-form-item label="价格信息" prop="costMessage">
                    <el-input v-model="saveCostForm.costMessage"></el-input>
                </el-form-item>
                <el-form-item label="单价" prop="costPrice">
                    <el-input v-model="saveCostForm.costPrice"></el-input>
                </el-form-item>
                <el-form-item label="所属商品" prop="styleWaresId" :rules="checkSelectCostWaresId">
                    <el-select v-model="selectSaveCostWaresIdForm.waresName" placeholder="请选择" popper-class="blueBack"
                        value-key="id" :popper-append-to-body="false" @change="selectSaveCostWaresId">
                        <el-option v-for="item in waresList" :key="item.id" :label="item.name" :value="item">
                            <div>{{ item.waresName }}</div>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属款式" prop="styleStyleId" :rules="checkSelectCostStyleId">
                    <el-select v-model="selectSaveCostStyleIdForm.styleName" placeholder="请选择" popper-class="blueBack"
                        :popper-append-to-body="false" value-key="id" @change="selectSaveCostStyleId">
                        <el-option v-for="item in styleList" :key="item.id" :label="item.name" :value="item">
                            {{ item.styleName }}
                        </el-option>
                    </el-select>
                </el-form-item>

                <div>
                    <div v-for="(item, index) in saveCostForm.costArr">
                        <el-row style="display: flex; align-items: center;">
                            <el-col :span="8">
                                <el-form-item label="价格信息" prop="costMessage">
                                    <el-input v-model="item.costMessage"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="单价" prop="waresPrice">
                                    <el-input v-model="item.waresPrice"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item>
                                    <el-button type="primary" icon="el-icon-plus" size="mini"
                                        @click="addSaveItems(saveCostForm.costArr.length)"
                                        v-if="index + 1 == saveCostForm.costArr.length"></el-button>
                                    <el-button type="danger" icon="el-icon-minus" size="mini"
                                        @click="deleteSaveItems(item, index)" v-if="index !== 0"></el-button>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>
                </div>

                <el-form-item>
                    <template slot-scope="scope">
                        <el-button type="primary" @click="saveCostData" :loading="loading">提交</el-button>
                        <el-button @click="closeSaveCostForm">取消</el-button>
                    </template>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 修改价格弹出框 -->
        <el-dialog title="修改商品价格" :visible.sync="showEditCostForm" :close-on-click-modal="false"
            @close="closeEditCostForm">
            <el-form ref="editCostForm" :model="editCostForm" label-width="100px" :rules="editCostRules">
                <el-form-item label="价格信息" prop="costMessage">
                    <el-input v-model="editCostForm.costMessage"></el-input>
                </el-form-item>
                <el-form-item label="单价" prop="waresPrice">
                    <el-input v-model="editCostForm.waresPrice"></el-input>
                </el-form-item>
                <el-form-item>
                    <template slot-scope="scope">
                        <el-button type="primary" @click="editCostData" :loading="loading">提交</el-button>
                        <el-button @click="closeEditCostForm">取消</el-button>
                    </template>
                </el-form-item>
            </el-form>
        </el-dialog>

        <div class="content">
            <el-table :data="costList" style="width: 100%;" stripe :default-sort="{ prop: 'date', order: 'ascending' }">
                <el-table-column label="详情信息">
                    <el-table-column label="价格名称" width="180" prop="costMessage">

                        <template slot-scope="scope">
                            <div>{{ scope.row.costMessage }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="单价" width="180" prop="waresPrice">
                        <template slot-scope="scope">
                            <div>{{ scope.row.waresPrice }}</div>
                        </template>
                    </el-table-column>

                </el-table-column>

                <el-table-column label="添加">
                    <el-table-column label="添加者">

                        <template slot-scope="scope">
                            <div>{{ scope.row.saveAdmin }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作时间" width="180" sortable prop="date">

                        <template slot-scope="scope">
                            <i class="el-icon-time" v-if="scope.row.saveTime != null"></i>
                            <span style="margin-left: 10px">{{ scope.row.saveTime }}</span>
                        </template>
                    </el-table-column>
                </el-table-column>

                <el-table-column label="删除">
                    <el-table-column label="删除者">

                        <template slot-scope="scope">
                            <div>{{ scope.row.removeAdmin }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="理由">

                        <template slot-scope="scope">
                            <div>{{ scope.row.removeMemo }}</div>
                        </template>
                    </el-table-column>
                </el-table-column>

                <el-table-column label="操作">
                    <el-table-column label="修改">

                        <template slot-scope="scope">
                            <el-button type="primary" circle icon="el-icon-edit"
                                @click="showEditCost(scope.row.id)"></el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">

                        <template slot-scope="scope">
                            <el-switch v-model="scope.row.isDelete"
                                @change="changeCostOnAndOffSwitch($event, scope.$index, scope.row)"
                                active-color="#66b1ff" inactive-color="#adadad" active-text="恢复" inactive-text="删除"
                                :active-value="0" :inactive-value="1">
                            </el-switch>
                            <el-switch v-model="scope.row.state"
                                @change="changeCostPutAndPullSwitch($event, scope.$index, scope.row)"
                                active-color="#66b1ff" inactive-color="#adadad" active-text="上架" inactive-text="下架"
                                :active-value="0" :inactive-value="1">
                            </el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column label="状态">

                        <template slot-scope="scope">
                            <el-tag type="success" effect="dark" v-if="scope.row.state == 0">启用</el-tag>
                            <el-tag type="info" effect="dark" v-if="scope.row.state == 1">下架</el-tag>
                            <el-tag type="danger" effect="dark" v-if="scope.row.state == 2">异常</el-tag>
                        </template>
                    </el-table-column>
                </el-table-column>
            </el-table>
            <el-pagination @size-change="costSizeChange" @current-change="costCurrentChange"
                :page-size="costListForm.size" :page-sizes="[10, 20, 30]" layout="total, sizes, prev, pager, next"
                :total="costTotal" style="margin-top: 20px;">
            </el-pagination>
        </div>
    </div>
</template>

<script>
import utils from '@/utils/checkLogin'
import { getAllWaresListBySelect, getAllStyleListBySelect, getAllCostList, getImagesList, getWaresBrandsList, saveCost, getUpdateCostInfo, editCost, offSaleCost, onSaleCost, pullCost, putCost } from '../../api/api'
import { jwtDecode } from 'jwt-decode'
import { Message } from 'element-ui'
export default {
    data() {
        return {
            loading: false,
            waresList: [],
            imagesList: [],
            costList: [],
            costTotal: 0,
            costListForm: {
                memo: '',
                page: 1,
                size: 10
            },
            showSaveCostForm: false,
            saveCostForm: {
                costMessage: '',
                costPrice: null,
                styleId: null,
                waresId: null
            },
            saveCostRules: {
                costMessage: [
                    { required: true, message: '请输入价格信息', trigger: 'change' }
                ],
                costPrice: [
                    { required: true, message: '请输入单价', trigger: 'change' },
                    { type: 'number', message: '输入的值必须为数字', trigger: 'blur', transform: (value) => Number(value) },
                ]
            },
            checkSelectCostWaresId: [{
                required: true,
                message: '请选择所属商品',
                validator: this.costWaresIdValidator
            }],
            checkSelectCostStyleId: [{
                required: true,
                message: '请选择所属款式',
                validator: this.costStyleIdValidator,
                trigger: ['blur', 'change'],
                type: 'string'
            }],
            showEditCostForm: false,
            editCostForm: {
                costId: null,
                styleId: null,
                costMessage: '',
                waresPrice: null
            },
            editCostRules: {
                costMessage: [
                    { required: true, message: '请输入价格信息', trigger: 'change' }
                ],
                waresPrice: [
                    { required: true, message: '请输入单价', trigger: 'change' },
                    { type: 'number', message: '输入的值必须为数字', trigger: 'blur', transform: (value) => Number(value) },
                ]
            },
            styleList: [],
            selectSaveCostWaresIdForm: {
                waresName: ''
            },
            selectSaveCostStyleIdForm: {
                styleName: ''
            },
        }
    },
    methods: {
        costWaresIdValidator(rule, value, callback) {
            if (this.selectSaveCostWaresIdForm.waresName === '') {
                callback(new Error('请选择所属商品'))
            } else {
                callback()
            }
        },
        costStyleIdValidator(rule, value, callback) {
            if (this.selectSaveCostStyleIdForm.styleName === '') {
                callback(new Error('请选择所属款式'))
            } else {
                callback()
            }
        },
        getAllWaresListBySelectData() {
            getAllWaresListBySelect().then((res) => {
                if (res.code == 200) {
                    this.waresList = res.data
                    console.log('全部商品列表', res);
                    // this.waresListTotal = res.data.total
                }
            })
        },
        getAllCostListData() {
            getAllCostList(this.costListForm).then((res) => {
                if (res.code == 200) {
                    console.log('全部商品价格', res)
                    this.costList = res.data
                    this.costTotal = res.total
                }
            })
        },
        costSizeChange(e) {
            this.costListForm.size = e
            this.getAllCostListData()
        },
        costCurrentChange(e) {
            this.costListForm.page = e
            this.getAllCostListData()
        },
        // 搜索
        styleSearch() {
            this.getAllCostListData()
        },
        // 如果搜索框的值为空，刷新一下价格列表
        checkVal() {
            if (this.costListForm.memo == '') {
                this.getAllCostListData()
            }
        },
        openSaveCostForm() {
            this.showSaveCostForm = true
            this.getAllWaresListBySelectData()
        },
        closeSaveCostForm() {
            this.showSaveCostForm = false
            console.log('关闭');
            this.$nextTick(() => {
                this.$refs.saveCostForm.resetFields()
                this.$set(this.selectSaveCostStyleIdForm, 'styleName', '')
                this.$set(this.selectSaveCostWaresIdForm, 'waresName', '')
            })
        },
        addSaveItems() {
            this.saveCostForm.costArr.push({
                costMessage: '',
                waresPrice: ''
            })
        },
        deleteSaveItems(item, index) {
            this.saveCostForm.costArr.splice(index, 1)
        },
        closeEditCostForm() {
            this.showEditCostForm = false
        },
        showEditCost(costId) {
            this.showEditCostForm = true
            this.getAllWaresListBySelectData()
            this.editCostForm.costId = costId
            let data = {
                costId
            }
            getUpdateCostInfo(data).then((res) => {
                if (res.code == 200) {
                    console.log('修改价格（数据回显）', res)
                    this.editCostForm.costMessage = res.data.costMessage
                    this.editCostForm.waresPrice = res.data.waresPrice
                    this.editCostForm.styleId = res.data.styleId
                }
            })

        },

        editCostData() {
            console.log(JSON.stringify(this.editCostForm))
            editCost(this.editCostForm).then((res) => {
                if (res.code == 200) {
                    Message({
                        message: '修改成功',
                        type: 'success',
                        duration: 3000
                    })
                    console.log('修改价格', res)
                    this.loading = true
                    setTimeout(() => {
                        this.showEditCostForm = false
                        this.loading = false
                        this.getAllCostListData()
                        // this.restSaveWaresForm()
                        this.$nextTick(() => {
                            this.$refs.editCostForm.resetFields()
                        })
                    }, 2000)

                } else {
                    Message(({
                        message: '修改失败',
                        type: 'success',
                        duration: 2000
                    }))
                }
            })
        },
        // 保存提交价格
        saveCostData() {
            this.$refs.saveCostForm.validate(valid => {
                if (!valid) {
                    Message({
                        message: '请检查表单',
                        type: 'warning',
                        duration: 2000,
                    })
                    return false
                } else {
                    console.log(JSON.stringify(this.saveCostForm))
                    this.$refs.saveCostForm.validate(valid => {
                        if (!valid) {
                            Message({
                                message: '请检查表单！',
                                type: 'warning',
                                duration: 2000
                            })
                            return false
                        } else {
                            saveCost(this.saveCostForm).then((res) => {
                                if (res.code == 200) {
                                    console.log('添加价格', res)
                                    Message({
                                        message: '添加成功',
                                        type: 'success',
                                        duration: 2000
                                    })
                                    this.getAllWaresListBySelectData()
                                    setTimeout(() => {
                                        this.showSaveCostForm = false
                                        this.$nextTick(() => {
                                            this.$refs.saveCostForm.resetFields()
                                            this.$set(this.selectSaveCostStyleIdForm, 'styleName', '')
                                            this.$set(this.selectSaveCostWaresIdForm, 'waresName', '')
                                        })
                                    }, 1500)
                                } else {
                                    Message({
                                        message: '添加成失败',
                                        type: 'warning',
                                        duration: 2000
                                    })
                                }
                            })
                        }
                    })
                }
            })

        },

        changeCostOnAndOffSwitch($event, index, row) {
            console.log('$event', $event);
            // 删除
            if ($event) {
                console.log('已删除');
                let removeCostForm = {
                    costId: row.id
                }
                this.$confirm('是否删除该价格?', '删除提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$prompt('请输入删除理由', '删除提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                    }).then(({ value }) => {
                        removeCostForm.removeMemo = value
                        console.log(JSON.stringify(removeCostForm));
                        offSaleCost(removeCostForm).then((res) => {
                            if (res.code == 200) {
                                console.log('删除成功', res);
                                this.$message({
                                    type: 'success',
                                    message: '删除成功',
                                    duration: 2000
                                })
                                setTimeout(() => {
                                    // this.showCostListForm = false
                                    this.getAllCostListData()
                                }, 1000)
                            } else {
                                this.$message({
                                    type: 'error',
                                    message: '删除失败',
                                    duration: 2000
                                })
                            }
                        })

                    }).catch(() => {
                        this.costList[index].isDelete = $event
                        this.getAllCostListData()
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    })
                    this.costList[index].isDelete = $event
                    this.getAllCostListData()
                })
            } else {
                // 恢复
                console.log('已恢复');
                let noRemoveCostForm = {
                    costId: row.id,
                }
                console.log(JSON.stringify(noRemoveCostForm));
                onSaleCost(noRemoveCostForm).then((res) => {
                    if (res.code == 200) {
                        console.log('恢复成功', res);
                        this.$message({
                            type: 'success',
                            message: '恢复成功',
                            duration: 2000
                        })
                        setTimeout(() => {
                            this.getAllCostListData()
                        }, 1000)
                    } else {
                        this.$message({
                            type: 'error',
                            message: '恢复失败',
                            duration: 2000
                        })
                    }
                })
            }
        },

        changeCostPutAndPullSwitch($event, index, row) {
            console.log('$event', $event);
            // 下架
            if ($event) {
                console.log('已下架');
                let pullCostForm = {
                    costId: row.id,
                }
                this.$confirm('是否下架该价格?', '下架提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$prompt('请输入下架理由', '下架提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                    }).then(({ value }) => {
                        pullCostForm.memo = value
                        console.log(JSON.stringify(pullCostForm));
                        pullCost(pullCostForm).then((res) => {
                            if (res.code == 200) {
                                console.log('下架成功', res);
                                this.$message({
                                    type: 'success',
                                    message: '下架成功',
                                    duration: 2000
                                })
                                setTimeout(() => {
                                    this.showCostListForm = false
                                    this.getAllCostListData()
                                }, 1000)
                            } else {
                                this.$message({
                                    type: 'error',
                                    message: '下架失败',
                                    duration: 2000
                                })
                            }
                        })

                    }).catch(() => {
                        this.costList[index].state = $event
                        this.getAllCostListData()
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消下架'
                    })
                    this.costList[index].state = $event
                    this.getAllCostListData()
                })
            } else {
                // 上架
                console.log('已上架');
                let noPullCostForm = {
                    costId: row.id,
                }
                console.log(JSON.stringify(noPullCostForm));
                putCost(noPullCostForm).then((res) => {
                    if (res.code == 200) {
                        console.log('上架成功', res);
                        this.$message({
                            type: 'success',
                            message: '上架成功',
                            duration: 2000
                        })
                        setTimeout(() => {
                            this.getAllCostListData()
                        }, 1000)
                    } else {
                        this.$message({
                            type: 'error',
                            message: '上架失败',
                            duration: 2000
                        })
                    }
                })
            }
        },
        getAllStyleListBySelectData(waresId) {
            // let obj = { waresId }
            getAllStyleListBySelect(waresId).then((res) => {
                if (res.code == 200) {
                    console.log('该商品的所有款式', res)
                    this.styleList = res.data
                    // this.styleListTotal = res.total
                }
            })
        },
        selectSaveCostWaresId(e) {
            this.selectSaveCostWaresIdForm.waresName = e.waresName
            this.saveCostForm.waresId = e.id
            this.getAllStyleListBySelectData(e.id)
        },
        selectSaveCostStyleId(e) {
            this.selectSaveCostStyleIdForm.styleName = e.styleName
            this.saveCostForm.styleId = e.id
        }
    },
    created() {
        utils.checkLogin()
        this.getAllCostListData()
    }
}
</script>

<style lang="less" scoped>
.app-container {
    padding: 40px;

    .header {
        align-items: center;
        display: flex;
        margin-bottom: 20px;

        .el-icon-search {
            cursor: pointer;
            margin-right: 4px;
            margin-top: 8px;
        }

    }

    .blueBack {
        .el-select-dropdown__item {
            // height: 80px;
        }
    }


    .content {
        text-align: center;

        .el-select-dropdown__item {
            height: auto;
        }
    }
}
</style>